<?php
// 应用公共文件
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\facade\Config;
use think\facade\Db;
use think\facade\Request;

function singleJson($arr, $error = '', $code = 200,$isLogin=true)
{
    $result = array('code' => $code);
    $result['data'] = $arr;

    if (!$arr && $code === 200) {
        $result['code'] = -1;

    }
    if (!$arr) {
        $result['error'] = $error;

    }

    $key = Config::get('app.key');

    $token = Request::header('token');

    if ($token) {

        try {
            $decoded = JWT::decode($token, new Key($key, 'HS256')); //HS256方式，这里要和签发的时候对
        } catch (\Exception $e) {
            $isLogin &&   $result['isLogin'] = -1;

        }
    }
//   $result['isLogin'] = -1;
    $result['time'] = date('Y-m-d H:i:s');
    $result['token'] = $token;
    echo json_encode($result);
    exit;
}

function listsJson($lists, $total, $code = 200, $error = '')
{
    $result = array('code' => $code);
    $result['data'] = $lists;
    $result['total'] = $total;
    if (!$lists) {
        $result['error'] = $error;
    }

    echo json_encode($result);
    exit;
}

function getParam($param, $field, $default = '')
{
    $result = $default;
    if (isset($param[$field]) && $param[$field]) {
        $result = $param[$field];
    }
    return $result;
}

function getSqlOrder($field, $val, $default)
{
    $result = $default;

    if ($field && $val) {
        if (in_array($val, ['ascending', 'descending'])) {
            $result = $field . " " . ($val === 'ascending' ? 'ASC' : 'DESC');
        } else {
            $result = $field . " " . $val;
        }

    }
    return $result;
}

function createUserToken($userId)
{
    $jwtContent = [
        // 签发人，这里采用当前站点域名
        'iss' => request()->domain(),
        // 签发时间，当前时间戳
        'iat' => time(),
        // 到期时间，1天后
        'exp' => time() + 3600 * 24,
        // 自定义数据
        'data' => [
            'user_id' => $userId
        ]
    ];
    // 自定义 key，用于加密 token，只保存在服务端，不可泄漏。
    $key = Config::get('app.key');

    return JWT::encode($jwtContent, $key, 'HS256');
}

function getSelectParams($fieldImplode)
{
    $fields = explode(",", $fieldImplode);
    $params = Request::param();

    $arr = [];
    foreach ($params as $k => $v) {
        if (in_array($k, $fields)) {
            if ($k === 'pwd') {
                $arr[$k] = changePwd($v);
            } else {
                $arr[$k] = $v;
            }
        }
    }
    return $arr;

}

function changePwd($pwd)
{
    return md5(md5($pwd));
}

function getConfig()
{
    $lists = Db::name('config')->field('val')->select();
    $result = [];
    foreach ($lists as $v) {
        $arr = json_decode($v['val'], true);
        foreach ($arr as $k2 => $v2) {
            $result[$k2] = $v2;
        }
    }
    return $result;
}

function getSingleField($table, $field, $val, $field2)
{
    $info = Db::name($table)->field('id')->where(array($field => $val))->find();

    $rs = isset($info[$field2]) ?? '';

    return $rs;

}

function getIsVip($userId){
    $is_vip = 0;
    if($userId){
        $userInfo = Db::name('users')->field('vip_time')->where(array('id' => $userId))->find();
        $is_vip = $userInfo['vip_time'] > date('Y-m-d') ? 1 : 0;
    }

    return $is_vip;
}

function getUserId()
{
    $key = Config::get('app.key');

    $token = Request::header('token');

    $userId = null;
    if(!$token){
        return $userId;
    }
    try {
        $decoded = JWT::decode($token, new Key($key, 'HS256')); //HS256方式，这里要和签发的时候对

        $userId =    $decoded->data->user_id;
    } catch (\Exception $e) {


    }

    return $userId;
}
function isLinux(){
    $isLinux = strpos(PHP_OS, "Linux") !== false;
    return $isLinux;
}

function getFileBei($id) {
    return (int)($id / 100) . "/";
}